package test.marui.com.mytest.utils;

import android.content.Context;
import android.graphics.Bitmap;
import android.os.Build;
import android.renderscript.Allocation;
import android.renderscript.Element;
import android.renderscript.RenderScript;
import android.renderscript.ScriptIntrinsicBlur;
import android.renderscript.ScriptIntrinsicResize;
import android.support.annotation.FloatRange;
import android.support.annotation.RequiresApi;

/**
 * Created by MR on 2019/1/25.
 */
class GaussianBlur {

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
    public static Bitmap blur(Context context, Bitmap originalBitmap, float radius) {

        if (radius <= 0) {
            return originalBitmap;
        }

        if (radius <= 25) {
            return blurIn25(context, originalBitmap, radius);
        }

        return blur(context, originalBitmap, 25, radius / 25);
    }

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
    public static Bitmap blur(Context context, Bitmap originalBitmap,
                              @FloatRange(from = 1.0, to = 25.0, fromInclusive = false) float radius,
                              float scale) {

        if (radius <= 0) {
            return originalBitmap;
        }

        if (scale == 1) {
            return blur(context, originalBitmap, radius);
        }

        int width = originalBitmap.getWidth();
        int height = originalBitmap.getHeight();
        Bitmap input = BitmapUtil.scale(originalBitmap, (int) (width / scale), (int) (height / scale));
        Bitmap resultBitmap = blur(context, input, radius);
        return BitmapUtil.scale(resultBitmap, width, height);
    }

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
    public static Bitmap blurIn25(Context context, Bitmap originalBitmap, float radius) {

        // 创建输出图片
        Bitmap blurBitmap = Bitmap.createBitmap(originalBitmap.getWidth(), originalBitmap.getHeight(), originalBitmap.getConfig());
        // 构建RenderScript对象，用来开辟内存来存储图片
        RenderScript renderScript = RenderScript.create(context);
        // 构建高斯模糊模板
        ScriptIntrinsicBlur scriptIntrinsicBlur = ScriptIntrinsicBlur.create(renderScript, Element.U8_4(renderScript));
        // 开辟输入内存
        Allocation originalAllocation = Allocation.createFromBitmap(renderScript, originalBitmap);
        // 开辟输出内存
        Allocation blurAllocation = Allocation.createFromBitmap(renderScript, blurBitmap);
        // 设置模糊半径
        scriptIntrinsicBlur.setRadius(radius);
        // 设置输入内存
        scriptIntrinsicBlur.setInput(originalAllocation);
        // 设置输出内存
        scriptIntrinsicBlur.forEach(blurAllocation);
        // 设置输出bitmap
        blurAllocation.copyTo(blurBitmap);
        // 销毁RenderScript对象
        renderScript.destroy();
        return blurBitmap;
    }

}
